package com.yonyou.iuap.controller.pc;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ListIterator;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yonyou.iuap.base.intf.IUserAdminService;
import com.yonyou.iuap.pub.DateUtil;
import com.yonyou.iuap.pub.JsonUtils;
import com.yonyou.iuap.shell.entity.BdKnowledgeCategoryEntity;
import com.yonyou.iuap.shell.entity.exp.BdKnowledgeCategoryEntityVo;
import com.yonyou.iuap.shell.entity.exp.FavoritePojo;
import com.yonyou.iuap.shell.pub.ResultDto;
import com.yonyou.iuap.shell.service.intf.IKnowledgeCategoryService;
/**
 * 知识类别
 * **/
@Controller
@RequestMapping("/PCKnowledgeCategoryEntity")
public class PCKnowledgeCategoryEntityController {
	private final Logger logger = (Logger) LoggerFactory.getLogger(getClass());
	private long start,end;
	@Autowired
	private IKnowledgeCategoryService iKnowledgeCategoryService;
	
	@Autowired
	private IUserAdminService userService;
	/**
	 * 获取所有知识类别
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="getAllKnowledgeCategory",method=RequestMethod.POST)
	@ResponseBody
	public String getAllKnowledgeCategory(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		List<BdKnowledgeCategoryEntityVo> dateList=iKnowledgeCategoryService.getAllKnowledgeCategory();
		
		ResultDto rsDto = new ResultDto();
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setNum(dateList==null?0:dateList.size());
		rsDto.setCount(dateList==null?0:dateList.size());
		rsDto.setData(dateList);
		end=System.currentTimeMillis();
		logger.info("getAllKnowledgeCategory接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
	
	@RequestMapping(value="getKnowledgeCategoryByCondition",method=RequestMethod.POST)
	@ResponseBody
	public String getFirstClass(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		String pk_user = map.get("pk_user")==null?"":map.get("pk_user").toString();
		String level=map.get("level").toString();
		ResultDto result=null;
		if("1".equals(level)){
			String sql="fw_level=0 and sealmark='Y' and PK_KNOWLEDGE_CATEGORY in (select PK_KNOWLEDGE_CATEGORY from shell_bd_category_relation where pk_user = '"+pk_user+"')";
			result=iKnowledgeCategoryService.selectByCondition(sql);
		}else if("2".equals(level)){
			 String str="sealmark='Y' and  fw_parent in (select pk_knowledge_category  from shell_bd_knowledge_category "
			 		+ "where  fw_level=0 and sealmark='Y') and  fw_parent='"+map.get("fw_parent")+"' and PK_KNOWLEDGE_CATEGORY in (select PK_KNOWLEDGE_CATEGORY from shell_bd_category_relation where pk_user = '"+pk_user+"')";  
			result=iKnowledgeCategoryService.selectByCondition(str);
		}
		end=System.currentTimeMillis();
		logger.info("getKnowledgeCategoryByCondition接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(result);
	}
	
	/**
	 * 获取当前知识所拥有的用户权限
	 * @param request
	 * @param response
	 * @return
	 */
	@RequestMapping(value="getAllKnowledgeCategoryRelation",method=RequestMethod.POST)
	@ResponseBody
	public String getAllKnowledgeCategoryRelation(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		ResultDto rsDto = new ResultDto();
		String pk_knowledge_category=map.get("pk_knowledge_category").toString();
		List<BdKnowledgeCategoryEntityVo> dateList=iKnowledgeCategoryService.getAllKnowledgeCategoryRelation(pk_knowledge_category);
		if(dateList == null || dateList.size() <= 0){
			rsDto.setStatus(1);
			rsDto.setMessage("暂无数据!");
			return JsonUtils.toJsonStr(rsDto);
		}
		
		StringBuffer pkUser=new StringBuffer();
		StringBuffer userName=new StringBuffer();
		for (int i = 0; i < dateList.size(); i++) {
			if(dateList.get(i).getPk_user()!= null && !dateList.get(i).getPk_user().equals("") )
				pkUser.append(dateList.get(i).getPk_user()).append(",");
			if(dateList.get(i).getUser_name() != null && !dateList.get(i).getUser_name().equals(""))
				userName.append(dateList.get(i).getUser_name()).append(",");
		}
		BdKnowledgeCategoryEntityVo data=new BdKnowledgeCategoryEntityVo();
		String s=pkUser.toString();
		String n=userName.toString();
		if(s != null && !s.equals(""))
			data.setPk_user(s.substring(0,s.length()-1));
		if(n != null  && !n.equals(""))
			data.setUser_name(n.substring(0,n.length()-1));
	
		rsDto.setStatus(0);
		rsDto.setMessage("数据查询成功!");
		rsDto.setData(data);
		end=System.currentTimeMillis();
		logger.info("getAllKnowledgeCategoryRelation接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
	
		
	/**
	 * 添加 （匹配有值的字段）
	 * @param supplier   知识类别表实体
	 * @param request
	 * @param response
	 * @return  
	 */
	@RequestMapping(value="insertCategory",method=RequestMethod.POST)
	@ResponseBody
	public String insertCategory(@RequestBody Map<String ,Object > map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		/*系统管理员权限校验 begin*/
		ResultDto userDto = userService.checkUserIsSys(map.get("userid")==null?"":map.get("userid").toString());
		if(userDto.getStatus()!=0){
			return JsonUtils.toJsonStr(userDto);
		}
		/*系统管理员权限校验 end*/
		BdKnowledgeCategoryEntityVo supplier = new BdKnowledgeCategoryEntityVo();
		supplier.setFw_parent(map.get("fw_parent").toString());  //父节点id
		supplier.setKnowledge_category_name(map.get("knowledge_category_name").toString()); //当前类别名称
		supplier.setPk_user(map.get("pk_user").toString());  //类别管理员
		supplier.setSealmark(map.get("sealmark").toString());  //封存标志是否启用
		if(StringUtils.isEmpty(map.get("fw_parent").toString())){
			supplier.setFw_level(0);
		}else{
			supplier.setFw_level(1);
		}
		
		ResultDto  rsDto = iKnowledgeCategoryService.insertCategory(supplier);
		end=System.currentTimeMillis();
		logger.info("insertCategory接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);

	}
	
	/**
	 * 通过id删除知识类别
	 * @param knowledgeCategory   知识类别表id 
	 * @param request
	 * @param response
	 * @return  
	 */
	@RequestMapping(value="deleteByPrimaryKey",method=RequestMethod.POST)
	@ResponseBody
	public String deleteByPrimaryKey(@RequestBody Map<String ,Object > map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		/*系统管理员权限校验 begin*/
		ResultDto userDto = userService.checkUserIsSys(map.get("userid")==null?"":map.get("userid").toString());
		if(userDto.getStatus()!=0){
			return JsonUtils.toJsonStr(userDto);
		}
		/*系统管理员权限校验 end*/
		String knowledgeCategory = map.get("knowledgeCategory").toString();
		ResultDto  rsDto = iKnowledgeCategoryService.deleteById(knowledgeCategory);
		end=System.currentTimeMillis();
		logger.info("deleteByPrimaryKey接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
		
	}
	
	/**
	 * 修改 （匹配有值的字段）
	 * @param supplier   知识类别表实体
	 * @param request
	 * @param response
	 * @return  
	 */
	@RequestMapping(value="updateByPrimaryKeySelective",method=RequestMethod.POST)
	@ResponseBody
	public String updateByPrimaryKeySelective(@RequestBody Map<String ,Object > map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		/*系统管理员权限校验 begin*/
		ResultDto userDto = userService.checkUserIsSys(map.get("userid")==null?"":map.get("userid").toString());
		if(userDto.getStatus()!=0){
			return JsonUtils.toJsonStr(userDto);
		}
		/*系统管理员权限校验 end*/
		BdKnowledgeCategoryEntityVo supplier = new BdKnowledgeCategoryEntityVo();
		supplier.setPk_knowledge_category(map.get("categoryId").toString());     //类别id
		supplier.setUpdate_date(DateUtil.formatDateTime(new Date()));
		supplier.setKnowledge_category_name(map.get("knowledge_category_name").toString()); //当前类别名称
		supplier.setPk_user(map.get("pk_user").toString());  //类别管理员
		supplier.setSealmark(map.get("sealmark").toString());  //封存标志是否启用
		supplier.setUpate_user(map.get("upate_user").toString());  //当前登录用户id
		ResultDto rsDto = iKnowledgeCategoryService.updateByParamKey(supplier);
		end=System.currentTimeMillis();
		logger.info("updateByPrimaryKeySelective接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
	
	/**
	 * 获取一级知识分类
	 * @param supplier   知识类别表实体
	 * @param request
	 * @param response
	 * @return  
	 */
	@RequestMapping(value = "/selectFisrt", method = RequestMethod.POST)
	@ResponseBody
	public String selectFirst(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response) {
		start=System.currentTimeMillis();
		ResultDto resultDto = iKnowledgeCategoryService.selectAll();
		filterFirst(resultDto);
		String rtn_json = JsonUtils.toJsonStr(resultDto);
		end=System.currentTimeMillis();
		logger.info("selectFisrt接口调用时间"+String.valueOf(end-start));
		return rtn_json;
	}

	/**
	 * 获取二级知识分类
	 * @param supplier   知识类别表实体
	 * @param request
	 * @param response
	 * @return  
	 */

	@RequestMapping(value = "/selectSecond", method = RequestMethod.POST)
	@ResponseBody
	public String selectSecond(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response) {
		start=System.currentTimeMillis();
		String fw_parent=map.get("fw_parent").toString();
		ResultDto resultDto = iKnowledgeCategoryService.selectAll();
		filterSecond(resultDto,fw_parent);
		String rtn_json = JsonUtils.toJsonStr(resultDto);
		end=System.currentTimeMillis();
		logger.info("selectSecond接口调用时间"+String.valueOf(end-start));
		return rtn_json;
	}
	
	
	/**
	 * 返回一级列表
	 * 构建前台需要json格式
	 * @param rsDto
	 */
	private void filterFirst(ResultDto rsDto){
		if(rsDto!=null && rsDto.getData()!=null){
			List<BdKnowledgeCategoryEntity> listvo = (List<BdKnowledgeCategoryEntity>) rsDto.getData();
			ListIterator<BdKnowledgeCategoryEntity> iter=listvo.listIterator();
			while(iter.hasNext()){
				BdKnowledgeCategoryEntity t=iter.next();
				if(t.getFw_level()>0)iter.remove();
			}
			rsDto.setData(listvo);
		}
	}
	
	/**
	 * 返回二级级列表
	 * 构建前台需要json格式
	 * @param rsDto
	 */
	private void filterSecond(ResultDto rsDto,String fw_parent){
		if(rsDto!=null && rsDto.getData()!=null){
			List<BdKnowledgeCategoryEntity> listvo = (List<BdKnowledgeCategoryEntity>) rsDto.getData();
			List<BdKnowledgeCategoryEntity> newVos = new ArrayList<BdKnowledgeCategoryEntity>();
			for(BdKnowledgeCategoryEntity vo:listvo){
				if(vo.getFw_parent()!=null&&vo.getFw_parent().equals(fw_parent)){
					newVos.add(vo);
				}
			}
			rsDto.setData(newVos);
		}
	}
	@RequestMapping(value="/queryAllKnowledgeCateTree")
	@ResponseBody
	public String queryAllKnowledgeCateTree(@RequestBody Map map,HttpServletRequest request,HttpServletResponse response){
		start=System.currentTimeMillis();
		ResultDto rsDto =iKnowledgeCategoryService.queryKnoledgeCateForTree();
		end=System.currentTimeMillis();
		logger.info("queryAllKnowledgeCateTree接口调用时间"+String.valueOf(end-start));
		return JsonUtils.toJsonStr(rsDto);
	}
	
}

